<template>
    <h1>登录页面</h1>
    <el-card style="width: 450px;margin: 0 auto;padding:20px 10px 0 0;">
      <el-form label-width="60px">
        <el-form-item label="用户名">
          <el-input placeholder="请输入用户名" v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input placeholder="请输入密码" type="password" v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width:100%;" @click="login()">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
</template>

<script setup>
import {ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";

//1.创建用户对象
const user = ref({username:'',password:''});
//2.创建登录方法
const login = ()=>{
  //3.将user对象转为查询字符串格式
  let data = qs.stringify(user.value);
  //4.给后端发请求
  axios.post('http://localhost:8080/v1/users/login',data)
      .then((response)=>{
        if (response.data.code==2002){
          console.log(response.data);
          //5.成功消息里添加用户昵称
          //response.data 是后端返回的JsonResult响应结果对象
          //response.data.data 是JsonResult对象的data属性值,也就是后端返回的userVO
          let user = response.data.data;
          ElMessage.success('登录成功!欢迎'+user.nickname+'回来!');
          //localStorage以字符串键值对的方式管理数据
          //我们可以将登录成功的用户信息存入,方便其它地方使用
          //user是JS对象,不是字符串,所以需要先转换成字符串再存入JSON.stringify(user)
          localStorage.setItem('user',JSON.stringify(user));
          router.push('/');
        }else{
          ElMessage.error(response.data.msg);
        }
      });
}

</script>

<style scoped>

</style>